package controller

import (
	"github.com/cn-ygf/go-admin/internal/action"
	"github.com/cn-ygf/go-admin/internal/modular/system/service"
	"github.com/cn-ygf/go-admin/internal/modular/system/vo"
	"github.com/cn-ygf/go-admin/pkg/utils"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

// NoticeController 公告管理
type NoticeController struct {
	Ctx iris.Context
}

// PostList 查询公告列表
func (c *NoticeController) PostList(req vo.QueryNoticeListReq) mvc.Result {
	if !hasPermi(c.Ctx, "system:notice:list") {
		return nil
	}
	if req.PageSize > 1000 {
		req.PageSize = 1000
	}
	list, total, err := service.NoticeService.QueryList(&req)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	return action.Data(map[string]any{
		"rows":  list,
		"total": total,
	})
}

// GetBy 根据id获取公告信息
func (c *NoticeController) GetBy(id int64) mvc.Result {
	if !hasPermi(c.Ctx, "system:notice:query") {
		return nil
	}
	notice, err := service.NoticeService.GetByID(int32(id))
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	return action.Data(notice)
}

// Put 修改公告
func (c *NoticeController) Put(req vo.EditNoticeReq) mvc.Result {
	if !hasPermi(c.Ctx, "system:notice:edit") {
		return nil
	}
	req.UpdateBy = getCurrentUser(c.Ctx).UserName
	err := service.NoticeService.Update(&req)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.Error(err.Error())
	}
	return action.OK()
}

// Post 添加公告
func (c *NoticeController) Post(req vo.AddNoticeReq) mvc.Result {
	if !hasPermi(c.Ctx, "system:notice:add") {
		return nil
	}
	req.CreateBy = getCurrentUser(c.Ctx).UserName
	err := service.NoticeService.Add(&req)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.Error(err.Error())
	}
	return action.OK()
}

// DeleteBy 删除公告
func (c *NoticeController) DeleteBy(idStr string) mvc.Result {
	if !hasPermi(c.Ctx, "system:notice:remove") {
		return nil
	}
	var (
		err error
	)
	ids := utils.IdsStrToInt32(idStr)
	if len(ids) < 1 {
		return action.ParamError()
	}

	err = service.NoticeService.Delete(ids)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.Error(err.Error())
	}
	return action.OK()
}
